//
//  RCBaseVC.m
//  RocketProject
//
//  Created by chen jiedan on 13-5-28.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCBaseVC.h"
#import "UIColor-Expanded.h"
#import "CommonDefines.h"
#import "MLNavigationController.h"

#define kDefaultTitleFontSize		      18

#define KEY_WINDOW  [[UIApplication sharedApplication]keyWindow]

@interface RCBaseVC ()

@end

@implementation RCBaseVC

@synthesize viewContainer = _viewContainer;
@synthesize returnBtn = _returnBtn;
@synthesize titleLabel = _titleLabel;
@synthesize titleLabelText = _titleLabelText;
@synthesize isAddRecoginzer = _isAddRecoginzer;
@synthesize blackMask = _blackMask;
@synthesize startTouch = _startTouch;
@synthesize recognizer = _recognizer;
@synthesize lastScreenShotView = _lastScreenShotView;
@synthesize backgroundShotView = _backgroundShotView;
@synthesize isMoving = _isMoving;
@synthesize titleFont = _titleFont;
@synthesize titleColor = _titleColor;
@synthesize hasTitleShadow = _hasTitleShadow;
@synthesize isIOS7 = _isIOS7;

static float sysVersion = 2.0;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        if ( sysVersion == 2.0 )
            sysVersion =[[[UIDevice currentDevice] systemVersion] floatValue];
        self.titleColor = [UIColor colorWithHex:0xFFFFFFFF];
        self.titleFont = [UIFont fontWithName:kFontNameHeiti size:kDefaultTitleFontSize];
        self.hasTitleShadow = YES;
        self.isAddRecoginzer = YES;
        self.isIOS7 = [[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0f ? YES : NO;
    }
    return self;
}

-(id)init{
    self = [super init];
    if (nil == self) {
        return nil;
    }
    if ( sysVersion == 2.0 )
        sysVersion =[[[UIDevice currentDevice] systemVersion] floatValue];
    self.titleColor = [UIColor colorWithHex:0xFFFFFFFF];
    self.titleFont = [UIFont fontWithName:kFontNameHeiti size:kDefaultTitleFontSize];
    self.hasTitleShadow = YES;
    self.isAddRecoginzer = YES;
    return self;
}

-(void)dealloc{
    
    self.returnBtn = nil;
    self.titleLabelText = nil;
    self.titleLabel = nil;
    self.blackMask = nil;
    self.recognizer = nil;
    self.lastScreenShotView = nil;
    self.backgroundShotView = nil;
    [super dealloc];
}

-(void)loadView{
    [super loadView];
    self.view.backgroundColor = [UIColor colorWithHex:0xfff4f4f4];
    [self hideOriNaviReturnBtn];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.

    
    
    if (_viewContainer == nil) {
        _viewContainer = [[UIView alloc] initWithFrame:self.view.bounds];
        _viewContainer.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        [self.view insertSubview:_viewContainer atIndex:0];
        [_viewContainer release];
    }
    
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSArray *viewControllersArray = [self.navigationController viewControllers];
    if (self.isAddRecoginzer && viewControllersArray && [viewControllersArray count]>1) {
        if (!_recognizer) {
            _recognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self
                                                                  action:@selector(paningGestureReceive:)];
            [_recognizer delaysTouchesBegan];
            [_recognizer setMaximumNumberOfTouches:1];
            [self.view addGestureRecognizer:_recognizer];
        }
        
    }
}

- (void)hideOriNaviReturnBtn
{

    NSArray *viewControllersArray = [self.navigationController viewControllers];
    if (viewControllersArray && [viewControllersArray count]>1){
        self.navigationItem.leftBarButtonItem = [self createBackBarButtonItem];
    }
}

-(UIBarButtonItem *) createBackBarButtonItem {
    self.returnBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *backImage = [UIImage imageNamed:@"image_titlebar_back_button"];
    UIImage *backPressedImage = [UIImage imageNamed:@"image_titlebar_back_button_pressed"];
    _returnBtn.frame = CGRectMake(0, 0, backImage.size.width+20, backImage.size.height+32);
    [_returnBtn setImage:backImage forState:UIControlStateNormal];
    [_returnBtn setImage:backPressedImage forState:UIControlStateHighlighted];
    [_returnBtn addTarget:self action:@selector(backBarButtonItemPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIView *leftView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(_returnBtn.bounds) + 15, CGRectGetHeight(_returnBtn.bounds))] autorelease];
    [leftView addSubview:_returnBtn];
    return [[[UIBarButtonItem alloc] initWithCustomView:leftView] autorelease];
}

-(UILabel *) createTitleView {
    self.titleLabel = [[[UILabel alloc] init] autorelease];
    _titleLabel.text = self.titleLabelText;
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.textColor = self.titleColor;
    _titleLabel.backgroundColor = [UIColor clearColor];
    _titleLabel.font = self.titleFont;
    if (self.hasTitleShadow) {
        _titleLabel.shadowColor = [UIColor colorWithHex:0xFFC2C2C2];
        _titleLabel.shadowOffset = CGSizeMake(0, 0.5);
    }
    [_titleLabel sizeToFit];
    return _titleLabel;
}


-(UIBarButtonItem *) createLeftBarButtonItemWithButton:(UIButton *) button {
    if (!button) {
        return nil;
    }
    
    if (CGRectEqualToRect(button.frame, CGRectZero)) {
        button.frame = CGRectMake(0, 0, 50, 28);
    }
    
    UIView *leftView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(button.bounds) + 10, CGRectGetHeight(button.bounds))] autorelease];
    [leftView addSubview:button];
    return [[[UIBarButtonItem alloc] initWithCustomView:leftView] autorelease];
}

-(UIBarButtonItem *) createRightBarButtonItemWithButton:(UIButton *) button {
    if (!button) {
        return nil;
    }
    
    if (CGRectEqualToRect(button.frame, CGRectZero)) {
        button.frame = CGRectMake(0, 0, 50, 32);
    }
    
    UIView *rightView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, CGRectGetHeight(button.bounds))] autorelease];
    rightView.backgroundColor = [UIColor clearColor];
    [rightView addSubview:button];
    return [[[UIBarButtonItem alloc] initWithCustomView:rightView] autorelease];
}

-(void) backBarButtonItemPressed:(id) sender {
    [self.navigationController popViewControllerAnimated:YES];
}

-(UIBarButtonItem *) createRightBarButtonItemWithButton:(UIButton *) button  withLabel:(UILabel*)label
{
    if (!button && !label)
    {
        return nil;
    }
    
    if (CGRectEqualToRect(button.frame, CGRectZero)) {
        button.frame = CGRectMake(0, 0, 44, 44);
    }
    
    UIView *rightView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, CGRectGetHeight(button.bounds))] autorelease];
    rightView.backgroundColor = [UIColor clearColor];
    [rightView addSubview:button];
    [rightView addSubview:label];
    
    return [[[UIBarButtonItem alloc] initWithCustomView:rightView] autorelease];
}

-(UIBarButtonItem *) createRightBarButtonItemWithButton:(UIButton *) button  withSecondButton:(UIButton*)secondButton
{
    if (!button && !secondButton)
    {
        return nil;
    }
    
    if (CGRectEqualToRect(button.frame, CGRectZero)) {
        button.frame = CGRectMake(0, 0, 44, 44);
    }
    if (CGRectEqualToRect(secondButton.frame, CGRectZero)) {
        secondButton.frame = CGRectMake(44, 0, 44, 44);
    }
    
    UIView *rightView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 93, CGRectGetHeight(button.bounds))] autorelease];
    rightView.backgroundColor = [UIColor clearColor];
    [rightView addSubview:button];
    [rightView addSubview:secondButton];
    
    return [[[UIBarButtonItem alloc] initWithCustomView:rightView] autorelease];
}

-(UIBarButtonItem *) createRightBarButtonItemWithButton:(UIButton *) button  withSecondButton:(UIButton*)secondButton withThirdButton:(UIButton *)thirdButton
{
    if (!button && !secondButton && !thirdButton)
    {
        return nil;
    }
    
    if (CGRectEqualToRect(button.frame, CGRectZero)) {
        button.frame = CGRectMake(0, 0, 44, 44);
    }
    if (CGRectEqualToRect(secondButton.frame, CGRectZero)) {
        secondButton.frame = CGRectMake(44, 0, 44, 44);
    }
    if (CGRectEqualToRect(thirdButton.frame, CGRectZero)) {
        thirdButton.frame = CGRectMake(88, 0, 44, 44);
    }
    
    UIView *rightView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 137, CGRectGetHeight(button.bounds))] autorelease];
    rightView.backgroundColor = [UIColor clearColor];
    [rightView addSubview:button];
    [rightView addSubview:secondButton];
    [rightView addSubview:thirdButton];
    
    return [[[UIBarButtonItem alloc] initWithCustomView:rightView] autorelease];
}


- (void)moveViewWithX:(float)x
{
    
    NSLog(@"Move to:%f",x);
    x = x>320?320:x;
    x = x<0?0:x;
    
    CGRect frame = self.navigationController.view.frame;
    frame.origin.x = x;
    self.navigationController.view.frame = frame;
    
    float scale = (x/6400)+0.95;
    float alpha = 0.4 - (x/800);
    
    _lastScreenShotView.transform = CGAffineTransformMakeScale(scale, scale);
    _blackMask.alpha = alpha;
    
}

#pragma mark - Gesture Recognizer -

- (void)paningGestureReceive:(UIPanGestureRecognizer *)recoginzer
{
    if (![self.navigationController isKindOfClass:[MLNavigationController class]]) {
        return;
    }
    // If the viewControllers has only one vc or disable the interaction, then return.
    if (self.navigationController.viewControllers.count <= 1) return;
    
    // we get the touch position by the window's coordinate
    CGPoint touchPoint = [recoginzer locationInView:recoginzer.view];
    
    touchPoint = [recoginzer.view convertPoint:touchPoint toView:KEY_WINDOW];
    
    // begin paning, show the backgroundView(last screenshot),if not exist, create it.
    if (recoginzer.state == UIGestureRecognizerStateBegan) {
        
        _isMoving = YES;
        _startTouch = touchPoint;
        
        if (!self.backgroundShotView)
        {
            CGRect frame = self.navigationController.view.frame;
            
            self.backgroundShotView = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width , frame.size.height)]autorelease];
            self.backgroundShotView.backgroundColor = [UIColor blackColor];
            [self.navigationController.view.superview insertSubview:self.backgroundShotView belowSubview:self.navigationController.view];
            
            _blackMask = [[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width , frame.size.height)];
            _blackMask.backgroundColor = [UIColor blackColor];
            [self.backgroundShotView addSubview:_blackMask];
        }
        
        self.backgroundShotView.hidden = NO;
        
        if (_lastScreenShotView) [_lastScreenShotView removeFromSuperview];
        
        UIImage *lastScreenShot = [((MLNavigationController *)(self.navigationController)).screenShotsList lastObject];
        _lastScreenShotView = [[UIImageView alloc]initWithImage:lastScreenShot];
        _lastScreenShotView.backgroundColor = [UIColor clearColor];
        [self.backgroundShotView insertSubview:_lastScreenShotView belowSubview:_blackMask];
        
        //End paning, always check that if it should move right or move left automatically
    }else if (recoginzer.state == UIGestureRecognizerStateEnded){
        
        if (touchPoint.x - _startTouch.x > 50)
        {
            [UIView animateWithDuration:0.3 animations:^{
                [self moveViewWithX:320];
            } completion:^(BOOL finished) {
                
                self.backgroundShotView.hidden = YES;
                CGRect frame = self.navigationController.view.frame;
                frame.origin.x = 0;
                self.navigationController.view.frame = frame;
                [self.navigationController popViewControllerAnimated:NO];
                
                _isMoving = NO;
                
                
            }];
        }
        else
        {
            [UIView animateWithDuration:0.3 animations:^{
                [self moveViewWithX:0];
            } completion:^(BOOL finished) {
                _isMoving = NO;
                self.backgroundShotView.hidden = YES;
            }];
            
        }
        return;
        
        // cancal panning, alway move to left side automatically
    }else if (recoginzer.state == UIGestureRecognizerStateCancelled){
        
        [UIView animateWithDuration:0.3 animations:^{
            [self moveViewWithX:0];
        } completion:^(BOOL finished) {
            _isMoving = NO;
            self.backgroundShotView.hidden = YES;
        }];
        
        return;
    }
    
    // it keeps move with touch
    if (_isMoving) {
        [self moveViewWithX:touchPoint.x - _startTouch.x];
    }
}

-(void) viewDidUnload
{
    _viewContainer = nil;
    [super viewDidUnload];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    // Release any cached data, images, etc that aren't in use.
    // 此处做兼容处理需要加上ios6.0的宏开关，保证是在6.0下使用的,6.0以前屏蔽以下代码，否则会在下面使用self.view时自动加载viewDidLoad
    if (sysVersion < 6.0f) return;
    
    // 是否是正在使用的视图
    
    if ([self isViewLoaded] && [self.view window] == nil)
    {
        // Add code to preserve data stored in the views that might be
        // needed later.
        [self viewDidUnload];
        
        // Add code to clean up other strong references to the view in
        // the view hierarchy.
        self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
    }
}



@end
